<?php

/**
 * descript:订单验证器
 * User: blue
 * Date: 2018/5/30 16:57
 */

namespace app\api\validate;

use app\lib\exception\ParamException;

class OrderValidate extends BaseValidate
{
    /*数组验证规则*/
    protected $rule=[
        'products'=>'require|orderProducts',
    ];
    /*子数组验证规则*/
    protected $singleRule=[
        'product_id'=>'require|mustPositive',
        'count'=>'require|mustPositive'
    ];

    /*自定义订单验证规则
    数据格式样例
  $products=[
        [
            'product_id'=>1,
            'count'=>3
        ],
        [
            'product_id'=>2,
            'count'=>3
        ],
        [
            'product_id'=>3,
            'count'=>3
        ]
    ];
    */
    protected function orderProducts($value){
        if(!is_array($value)){
            throw new ParamException(['msg'=>'商品订单参数错误']);
        }
        if(empty($value)){
            throw new ParamException(['msg'=>'商品订单不能为空']);
        }
        //子数组的验证,验证器的嵌套
        foreach ($value as $v){
            $validate=new BaseValidate($this->singleRule);
            $res=$validate->batch()->check($v);
            if(!$res){
                throw new ParamException(['msg'=>$validate->getError()]);
            }
        }
        return true;
    }
}